import { _decorator, Component, director, math, Node, NodeEventType, Sprite, tween, v3, Widget } from 'cc';
import { events } from '../Enums';
import { ResMgr } from '../manager/ResMgr';
const { ccclass, property } = _decorator;

@ccclass('CashItem')
export class CashItem extends Component {
    start() {

    }

    update(deltaTime: number) {
        
    }

    protected onLoad(): void {
        director.on(events.update_cash, this.updateCash, this);
    }

    // 更新现金
    updateCash(cash: number,playAnim:boolean = true) {
        // 获取Label组件，并将其字符串设置为cash的字符串表示
        const rangeX:number = 50;
        const rangeY:number = 100;

        if(playAnim){
            this.schedule(async ()=>{
                let flyCash:Node = await this.createFlyCash();
                const posX:number = math.randomRangeInt(-rangeX,rangeX);
                const posY:number = math.randomRangeInt(-rangeY,-50);
                tween(flyCash)
                    .to(0.5,{position:v3(posX,posY,0)},{easing:'cubicOut'})
                    .to(1,{position:this.node.position},{easing:'backIn'})
                    .call(()=>{
                        flyCash.destroy();
                    })
                    .start();
            },0.1,5);
        }
    }

    public createFlyCash():Promise<Node>{
        return new Promise(async (resolve,reject)=>{
            let flyCash = new Node();
            const sp:Sprite = flyCash.addComponent(Sprite);
            sp.spriteFrame = await ResMgr.getSpriteRes("icon_cash_1","game/common/");
            this.node.parent.addChild(flyCash);
            resolve(flyCash);
        })
    }

    protected onDestroy(): void {
        director.off(events.update_cash, this.updateCash, this);
    }
}


